package com.atguigu.gulimall.cart.interceptor;


import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 在目标方法前拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResVo memberResVo = (MemberResVo) session.getAttribute(AuthServerConstant.LONGIN_USER);

        if(memberResVo != null){
            //用户登录
           userInfoTo.setUserId(memberResVo.getId());

        }

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if(name.equals(CartConstant.TMP_USER_COOKIE_NAME)){
                userInfoTo.setUserkey(cookie.getValue());
                userInfoTo.setTempUser(true);
            }
        }

        if(StringUtils.isEmpty(userInfoTo.getUserkey())){
            String s = UUID.randomUUID().toString();
            userInfoTo.setUserkey(s);
        }


        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 方法执行后，第一次登录就会创建一个临时用户
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();
     if(!userInfoTo.isTempUser()){
         Cookie cookie = new Cookie(CartConstant.TMP_USER_COOKIE_NAME,userInfoTo.getUserkey());

         cookie.setDomain("gulimall.com");
         cookie.setMaxAge(CartConstant.tempUser_timeout);

         response.addCookie(cookie);
     }
    }
}
